import axios, { AxiosInstance } from "axios";
import { MjcRequestInterceptors, MjcRequestConfig } from "./type";
import { AxiosResponse } from "axios";
import { message } from "antd";
class MJCrequest {
  instance: AxiosInstance;
  interceptors?: MjcRequestInterceptors;
  messageToast?: Boolean;
  constructor(config: MjcRequestConfig) {
    this.instance = axios.create(config);
    this.interceptors = config?.interceptors;
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    );
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    );

    this.instance.interceptors.request.use(
      (config) => {
        return config;
      },
      (err) => {
        console.log(err);
        return err;
      }
    );

    this.instance.interceptors.response.use(
      (res) => {
        return res;
      },
      (err) => {
        return Promise.reject(err);
      }
    );
  }
  request<T = AxiosResponse>(config: MjcRequestConfig<T>): Promise<T> {
    // if (config.interceptors?.requestInterceptor) {
    //   config = config.interceptors.requestInterceptor(config);
    // }
    this.messageToast = config?.isMessageToast || false;
    return new Promise((resolve, reject) => {
      this.instance
        .request<any, T>(config)
        .then((res) => {
          if (config.interceptors?.responseInterceptor) {
            config = config.interceptors.responseInterceptor(res);
          }
          resolve(res);
          return res;
        })
        .catch((err) => {
          //请求失败触发
          reject(JSON.parse(err.request.response));
          if (this.messageToast) {
            message.error(JSON.parse(err.request.response).message);
          }

          return JSON.parse(err.request.response).message;
        });
    });
  }

  get<T>(config: MjcRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: "GET" });
  }
  post<T>(config: MjcRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: "POST" });
  }
  patch<T>(config: MjcRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: "PATCH" });
  }
  put<T>(config: MjcRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: "PUT" });
  }
  delete<T>(config: MjcRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: "DELETE" });
  }
}

export default MJCrequest;
